import React, { useEffect, useState } from 'react';
import { Table, Input, 
  InputNumber, Popconfirm, 
  Form, Typography,
  Modal,Button, message,Spin, Space,Upload, Tag,TreeSelect,Tree
} from 'antd';
import { LoadingOutlined, PlusOutlined  } from '@ant-design/icons';
import {userList,userUpdate,userDelete,userInputAdd,userAdimnList,
  userAdminMenuInputAdd,
  userAdminMenuUpdate
} from '../../services/user-list/userListApi'
import { userLogins } from '@/services/user-login/userLogin';
import styles from './UserTableList.less';
import { isNull } from 'lodash';
import Item from 'antd/lib/list/Item';
import ImgCrop from 'antd-img-crop';
import { userMenuList,userJurisdictionMenuList } from '@/services/user-menu/userMenu';
import routes from '../routes'
import moment from 'moment';
import request from '../../services/request-api/index'

interface Item {
  id: number;
  userName: string;
  passWord: string;
  zgEmail: string;
  telephone: string;
  address: string;
  headerImg:string;
}

interface JurisdictionMenu{
  id: number;
  value: string;
  key: string;
  title: string;
  children: any[];
}

interface UserAdmin {
  id?: number;
  adminUserName: string;
  passWord: string;
  createTime?: string;
  updateTime?: string;
  menuList?: any;
  dFlag?: number;
  menuListString?:[]
}

const Index = () => {

  const treeData = [
    {
        "id": 1,
        "title": "首页数据",
        "value": "/welcome",
        "key": "1",
        "children": []
    },
    {
        "id": 2,
        "title": "管理页",
        "value": "/admin",
        "key": "2",
        "children": [
            {
                "id": 3,
                "title": "管理菜单一",
                "value": "/admin/sub-page",
                "key": "3",
                "children": []
            },
            {
                "id": 12,
                "title": "管理菜单二",
                "value": "/admin/sub-page2",
                "key": "12",
                "children": []
            }
        ]
    },
    {
        "id": 10,
        "title": "标准列表",
        "value": "/listuseritem",
        "key": "10",
        "children": []
    },
    {
        "id": 5,
        "title": "用户管理",
        "value": "/listuser",
        "key": "5",
        "children": []
    },
    {
        "id": 11,
        "title": "权限管理",
        "value": "/adminuser",
        "key": "11",
        "children": []
    },
    {
      "id": 13,
      "title": "礼物中心",
      "value": "/goods",
      "key": "13",
      "children": [
          {
              "id": 14,
              "title": "积分管理",
              "value": "/goods/goods-page",
              "key": "14",
              "children": []
          },
          {
              "id": 15,
              "title": "兑换记录",
              "value": "/goods/goods-page2",
              "key": "15",
              "children": []
          }
      ]
  },
  {
    "id": 16,
    "title":"在线客服",
    "value": '/onlineService',
    "key":"16",
    "children": []
  },
  {
    "id": 17,
    "title":"Excel表格列表",
    "value": '/exceltable',
    "key":"17",
    "children": []
  }

]

  const [form] = Form.useForm();
  const [data, setData] = useState<Item[]>([]);
  const [editingKey, setEditingKey] = useState(0);
  const [isModalVisible, setIsModalVisible] = useState(false);
  const [user,setTableUser] = useState<UserAdmin>({});
  const [userNull,setUserNull] = useState<UserAdmin>({})
  const [userName,setUserName] = useState<string>("")
  const [passWord,setPassWord] = useState<string>("")
  const [zgEmail,setEmail] = useState<string>("")
  const [telephone,setTelephone] = useState<string>("")
  const [address,setAddress] = useState<string>("")
  const [searchInput,setSearchInput] = useState("")
  const [fileList, setFileList] = useState([]);
  const [header,setHeader] = useState("")
  const [page,setPage] = useState(1)
  const [limit,setLimit] = useState(10)
  const [total,setTotal] = useState(0);
  const [menuList,setMenuList] = useState<string[]>();

  const [adminMenu,setAdminMenu] = useState<JurisdictionMenu[]>()
  const [userAdmins,setUserAdmin] = useState<UserAdmin[]>()

  
  const [expandedKeys, setExpandedKeys] = useState<React.Key[]>();
  const [checkedKeys, setCheckedKeys] = useState<React.Key[]>();
  const [selectedKeys, setSelectedKeys] = useState<React.Key[]>([]);
  const [autoExpandParent, setAutoExpandParent] = useState<boolean>(true);
  const [menuUser,setMenuUser] = useState<string[]>()

  useEffect(()=>{
    async function userLists(){
      const params = {
        page:page,
        limit:limit,
      }
      const users = await userList(params);
      console.log(users.list)
      const jurisdictionMenuList = await userJurisdictionMenuList();
      console.log(jurisdictionMenuList)
      const userAdmin = await userAdimnList();
      console.log(userAdmin)
      await setUserAdmin(userAdmin)
      await setAdminMenu(jurisdictionMenuList)
      await setTotal(users.total)
      await setData(users.list)
      await setTableUser(userNull)
     
      // console.log(new Date(parseInt("1628651677")*1000))
      // console.log("1628651677")
      
    }
    userLists()
    setSearchInput("")
  },[])


  //model data
  const showModal =async (e:UserAdmin) => {
    setIsModalVisible(true);

    console.log(checkedKeys)
    console.log(e)
    //debugger
    if(e.id){
      setTableUser(e)
      setUserName(e.adminUserName)
      setPassWord(e.passWord)
      setCheckedKeys(e.menuListString)
    }else{
      setUserName("")
      setPassWord("")
      setTableUser(userNull)
      setCheckedKeys([])
    }
  };

  const handleOk =async () => {

    setIsModalVisible(false);
    
    let formInpu = {
      id:user.id,
      adminUserName:userName,
      passWord:passWord,
      menuList:checkedKeys+""
    }

    if(!user.id){
      let formInputAdd = {
        adminUserName:userName,
        passWord:passWord,
        menuList:checkedKeys+""
      }
 
      await userAdminMenuInputAdd(formInputAdd)
      
    }else{

      await userAdminMenuUpdate(
        formInpu
       );
       
    }

    const userAdmin = await userAdimnList();
    await setUserAdmin(userAdmin)
    
  };

  const handleCancel= async ()=>{

    await setIsModalVisible(false);

    await setTableUser(userNull)

    await setFileList([])

    await setCheckedKeys([]);
 
  }

  const searchOnClick = async()=>{
    console.log(searchInput)
    let formInpu = {
      userName:searchInput,
      page:page,
      limit:limit
    }

    if(formInpu.userName){
      const users = await userList(formInpu);
      await setData(users.list)
      await setTotal(users.total)
    }else{
      const users = await userList({page:page,limit:limit});
      await setData(users.list)
      await setTotal(users.total)
    }
  }

  const cancel = async()=>{
    await setTableUser(userNull)
    await setFileList([])
  }

  const deleteModel= async (e:Item)=>{
    console.log(e.id)
    const deleteResponse = await userDelete(e.id);
    console.log(deleteResponse)
    if(deleteResponse === 1){
      const userListResponse = await userList({page:page,limit:limit});
      await setData(userListResponse.list);
      await setTotal(userListResponse.total)
    }
  }

  const onShowSizeChange =async(e:any)=>{
    console.log(e)
    setPage(parseInt(e.current))
    const param = {
      page:parseInt(e.current),
      limit:limit
    }
    const responseUsers = await userList(param); 
    setData(responseUsers.list)
  }

  const isEditing = (record: UserAdmin) => record.id === editingKey;

  const save = async (key: React.Key) => {
    try {
      const row = (await form.validateFields()) as Item;
      const newData = [...data];
      const index = newData.findIndex(item => key === item.id); // item.key
      if (index > -1) {
        const item = newData[index];
        newData.splice(index, 1, {
          ...item,
          ...row,
        });
        setData(newData);
        setEditingKey(0);
      } else {
        newData.push(row);
        setData(newData);
        setEditingKey(0);
      }
    } catch (errInfo) {
      console.log('Validate Failed:', errInfo);
    }
  };

  const columns = [
    {
      title: '序号',
      dataIndex: 'id',
      width: '10%',
      editable: true,
    },
    {
      title: '用户名',
      dataIndex: 'adminUserName',
      width: '10%',
      editable: true,
    },
    {
      title: '密码',
      dataIndex: 'passWord',
      width: '10%',
      editable: true,
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
      width: '10%',
      editable: true,
      render:createTime => <span>{moment(new Date(parseInt(createTime))).format("YYYY-MM-DD")}</span>
    },
    {
      title: '修改时间',
      dataIndex: 'updateTime',
      width: '10%',
      editable: true,
      render:updateTime => <span>{moment(new Date(parseInt(updateTime))).format("YYYY-MM-DD")}</span>
    },
    {
      title: '操作',
      dataIndex: 'operation',
      render: (_: any, record: UserAdmin) => {
        const editable = isEditing(record);
        return editable ? (
          <span>
            <a href="javascript:;" onClick={() => save(record.id)} style={{ marginRight: 8 }}>
              Save
            </a>
            <Popconfirm title="Sure to cancel?" onConfirm={cancel}>
              <a>Cancel</a>
            </Popconfirm>
          </span>
        ) : (
         <div>
            <Typography.Link disabled={editingKey !== 0} onClick={()=>showModal(record)}>
              <Button type="primary">授权</Button>
            </Typography.Link>
            <span>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</span>
            <Typography.Link disabled={editingKey !== 0} 
            >
              <Popconfirm title="真的要删除吗？" cancelText="不不不"  okText="是的" onConfirm={()=>deleteModel(record)}>
                <a href="#">Delete</a>
              </Popconfirm>
            </Typography.Link>
         </div>
        );
      },
    },
  ];


  const onExpand = (expandedKeysValue: React.Key[]) => {
    console.log('onExpand', expandedKeysValue);
    setExpandedKeys(expandedKeysValue);
    setAutoExpandParent(false);
  };

  const onCheck = (checkedKeysValue: React.Key[]) => {
    console.log('onCheck', checkedKeysValue);
    setCheckedKeys(checkedKeysValue);
    
  };

  const onSelect = (selectedKeysValue: React.Key[], info: any) => {
    console.log('onSelect', info);
    setSelectedKeys(selectedKeysValue);
  };

  return (
   <div>
     {/* search */}
      <div style={{display:"flex",flexDirection:"row",justifyContent:"space-between"}}>
      <div style={{display:"flex",flexDirection:"row",justifyContent:"flex-start"}}><Input placeholder="请输入您要搜索的内容!" 
      maxLength={10} onChange={txt=>setSearchInput(txt.target.value)} 
      value={searchInput} allowClear></Input><Button type="primary" onClick={searchOnClick}>搜索</Button></div>
      <div><Button type="primary" onClick={()=>showModal(user)}>新增</Button></div>
      </div>

    <Modal 
    centered
    title={user.id?"修改":"新增"} visible={isModalVisible} onOk={handleOk} onCancel={handleCancel}
    width={1000}
    >
    <p>用户名:<Input type="text" placeholder="请输入用户名" value={userName} 
    onChange={txt=>setUserName(txt.target.value)}></Input></p>
   
    <p>密码:<Input type="text" placeholder="请输入密码" value={passWord} 
    onChange={txt=>setPassWord(txt.target.value)}
    ></Input></p>
     <Tree
      checkable
      onExpand={onExpand}
      expandedKeys={expandedKeys}
      autoExpandParent={autoExpandParent}
      onCheck={onCheck}
      checkedKeys={checkedKeys}
      onSelect={onSelect}
      selectedKeys={selectedKeys}
      treeData={treeData}
    />
    </Modal>
    <Table 
    bordered
    columns={columns} 
    dataSource={userAdmins}
    // pagination={{
    //   onChange: cancel,
    //   defaultCurrent:1,
    //   pageSize:limit,
    //   total:total
    // }}
    onChange={onShowSizeChange}
     />   
   </div>
  );
};

export default Index;
